package com.basic.controller;


import com.basic.util.TokenUtil;
import com.code.domain.AjaxResult;
import com.code.entity.User;
import com.code.service.IUserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

@Controller
@Slf4j
@CrossOrigin
@ApiOperation(value = "基础数据",notes = "基础数据")
@RequestMapping(value = "/login/jwt")
public class LoginJWTController {

    @Resource
    private IUserService userService;

    @PostMapping("/login/login")
    public @ResponseBody AjaxResult login(User user) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        try{
            if(userService.login(user)){
                String token = TokenUtil.getJwtToken(user.getUsername(),user.getPassword());
                if(token != null){
                    return  AjaxResult.success("登录成功",token);
                }
            }
        }catch (UnknownAccountException e){ // 用户名不存在
            return AjaxResult.error("登录失败","用户名错误");
        }catch (IncorrectCredentialsException e){ // 密码错误
            return AjaxResult.error("登录失败","密码错误");
        }catch (AccountException e){ // 密码错误
            return AjaxResult.error("登录失败","帐号或密码不正确！");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    @PostMapping("/login/getList")
    public List<User> getList(HttpServletRequest request){
        List userList = userService.queryBasicUserAll();
        String id =  TokenUtil.getMemberIdByJwtToken(request);
        return userList;
    }

    @PostMapping("/login/getUser")
    public @ResponseBody AjaxResult getUser(HttpServletRequest request){
        String userid = TokenUtil.getMemberIdByJwtToken(request);
        //根据用户id 查询数据
        User user =  userService.queryUserName(userid);
        return AjaxResult.success("操作成功",user);
    }




}
